import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class test1 {
    private JFrame frame;
    private JTextField projectNameField;
    private JTextField addNameField;  // 新增奖项时的姓名输入
    private JTextField queryNameField;  // 查询时的姓名输入
    private JRadioButton aClassRadio;
    private JRadioButton bClassRadio;
    private JRadioButton cClassRadio;
    private JRadioButton nationalRadio;
    private JRadioButton provincialRadio;
    private JRadioButton firstPrizeRadio;
    private JRadioButton secondPrizeRadio;
    private JRadioButton thirdPrizeRadio;
    private JComboBox<Integer> personalRankCombo;
    private JComboBox<Integer> totalTeamCombo;
    private JButton addAwardButton;
    private JButton queryButton;
    private JTable awardTable;
    private DefaultTableModel tableModel;  // 主表格模型（显示所有数据）
    private DefaultTableModel queryTableModel;  // 查询专用表格模型（只显示个人数据）
    private JLabel totalScoreLabel;  // 显示所有记录的累计分
    private JLabel personalTotalLabel;  // 显示当前查询人的总分
    private List<Award> awardList;  // 存储所有奖项记录
    private Map<String, Double> studentTotalScores;  // 缓存每个学生的总分

    // 贡献度量化表（每行总和为1.0）
    private final double[][] contributionTable = {
            {1.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00},  // 总人数1
            {0.65, 0.35, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00},  // 总人数2
            {0.50, 0.25, 0.20, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00},  // 总人数3
            {0.50, 0.25, 0.15, 0.10, 0.05, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00},  // 总人数4
            {0.50, 0.25, 0.10, 0.10, 0.05, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00},  // 总人数5
            {0.45, 0.20, 0.10, 0.10, 0.10, 0.05, 0.00, 0.00, 0.00, 0.00, 0.00},  // 总人数6
            {0.40, 0.20, 0.10, 0.10, 0.10, 0.05, 0.05, 0.00, 0.00, 0.00, 0.00},  // 总人数7
            {0.38, 0.20, 0.10, 0.10, 0.10, 0.05, 0.05, 0.02, 0.00, 0.00, 0.00},  // 总人数8
            {0.38, 0.20, 0.10, 0.10, 0.10, 0.05, 0.05, 0.01, 0.01, 0.00, 0.00},  // 总人数9
            {0.38, 0.20, 0.10, 0.10, 0.10, 0.05, 0.04, 0.01, 0.01, 0.01, 0.00},  // 总人数10
            {0.38, 0.20, 0.10, 0.10, 0.10, 0.04, 0.04, 0.01, 0.01, 0.01, 0.01}   // 总人数11
    };

    public test1() {
        awardList = new ArrayList<>();
        studentTotalScores = new HashMap<>();
        initUI();
    }

    private void initUI() {
        frame = new JFrame("学科竞赛加分计算器");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new BorderLayout(10, 10));
        frame.setSize(1000, 700);
        frame.setLocationRelativeTo(null);

        // 顶部输入面板
        JPanel inputPanel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.fill = GridBagConstraints.HORIZONTAL;

        // 1. 新增奖项区域
        gbc.gridx = 0;
        gbc.gridy = 0;
        inputPanel.add(new JLabel("项目名称:"), gbc);
        gbc.gridx = 1;
        gbc.gridy = 0;
        projectNameField = new JTextField(20);
        inputPanel.add(projectNameField, gbc);

        gbc.gridx = 2;
        gbc.gridy = 0;
        inputPanel.add(new JLabel("学生姓名:"), gbc);
        gbc.gridx = 3;
        gbc.gridy = 0;
        addNameField = new JTextField(10);  // 新增奖项专用姓名输入
        inputPanel.add(addNameField, gbc);

        // 奖项大类
        gbc.gridx = 0;
        gbc.gridy = 1;
        inputPanel.add(new JLabel("奖项大类:"), gbc);
        gbc.gridx = 1;
        gbc.gridy = 1;
        aClassRadio = new JRadioButton("A类");
        bClassRadio = new JRadioButton("B类");
        cClassRadio = new JRadioButton("C类");
        ButtonGroup classGroup = new ButtonGroup();
        classGroup.add(aClassRadio);
        classGroup.add(bClassRadio);
        classGroup.add(cClassRadio);
        JPanel classPanel = new JPanel();
        classPanel.add(aClassRadio);
        classPanel.add(bClassRadio);
        classPanel.add(cClassRadio);
        inputPanel.add(classPanel, gbc);

        // 奖项级别
        gbc.gridx = 2;
        gbc.gridy = 1;
        inputPanel.add(new JLabel("奖项级别:"), gbc);
        gbc.gridx = 3;
        gbc.gridy = 1;
        nationalRadio = new JRadioButton("国家级");
        provincialRadio = new JRadioButton("省部级");
        ButtonGroup levelGroup = new ButtonGroup();
        levelGroup.add(nationalRadio);
        levelGroup.add(provincialRadio);
        JPanel levelPanel = new JPanel();
        levelPanel.add(nationalRadio);
        levelPanel.add(provincialRadio);
        inputPanel.add(levelPanel, gbc);

        // 奖项等次
        gbc.gridx = 0;
        gbc.gridy = 2;
        inputPanel.add(new JLabel("奖项等次:"), gbc);
        gbc.gridx = 1;
        gbc.gridy = 2;
        firstPrizeRadio = new JRadioButton("一等奖");
        secondPrizeRadio = new JRadioButton("二等奖");
        thirdPrizeRadio = new JRadioButton("三等奖");
        ButtonGroup prizeGroup = new ButtonGroup();
        prizeGroup.add(firstPrizeRadio);
        prizeGroup.add(secondPrizeRadio);
        prizeGroup.add(thirdPrizeRadio);
        JPanel prizePanel = new JPanel();
        prizePanel.add(firstPrizeRadio);
        prizePanel.add(secondPrizeRadio);
        prizePanel.add(thirdPrizeRadio);
        inputPanel.add(prizePanel, gbc);

        // 个人排名与合作总人数
        gbc.gridx = 2;
        gbc.gridy = 2;
        inputPanel.add(new JLabel("个人排名:"), gbc);
        gbc.gridx = 3;
        gbc.gridy = 2;
        List<Integer> rankList = new ArrayList<>();
        for (int i = 1; i <= 11; i++) rankList.add(i);
        personalRankCombo = new JComboBox<>(rankList.toArray(new Integer[0]));
        inputPanel.add(personalRankCombo, gbc);

        gbc.gridx = 0;
        gbc.gridy = 3;
        inputPanel.add(new JLabel("合作总人数:"), gbc);
        gbc.gridx = 1;
        gbc.gridy = 3;
        totalTeamCombo = new JComboBox<>(rankList.toArray(new Integer[0]));
        inputPanel.add(totalTeamCombo, gbc);

        // 2. 查询区域（独立于新增奖项）
        gbc.gridx = 2;
        gbc.gridy = 3;
        inputPanel.add(new JLabel("查询姓名:"), gbc);
        gbc.gridx = 3;
        gbc.gridy = 3;
        queryNameField = new JTextField(10);  // 查询专用姓名输入
        inputPanel.add(queryNameField, gbc);

        // 新增奖项按钮
        gbc.gridx = 4;
        gbc.gridy = 3;
        addAwardButton = new JButton("新增奖项");
        addAwardButton.addActionListener(e -> addAward());
        inputPanel.add(addAwardButton, gbc);

        // 查询按钮
        gbc.gridx = 5;
        gbc.gridy = 3;
        queryButton = new JButton("查询个人总分");
        queryButton.addActionListener(e -> queryPersonalScores());
        inputPanel.add(queryButton, gbc);

        frame.add(inputPanel, BorderLayout.NORTH);

        // 中间表格区域（默认显示所有记录，查询时切换为个人记录）
        String[] columnNames = {"项目名称", "奖项大类", "奖项级别", "奖项等次", "个人排名", "合作总人数", "单项加分"};
        tableModel = new DefaultTableModel(columnNames, 0);  // 总表模型
        queryTableModel = new DefaultTableModel(columnNames, 0);  // 个人查询表模型
        awardTable = new JTable(tableModel);  // 默认显示总表
        JScrollPane scrollPane = new JScrollPane(awardTable);
        frame.add(scrollPane, BorderLayout.CENTER);

        // 底部统计区域（区分总累计和个人累计）
        JPanel bottomPanel = new JPanel(new BorderLayout(20, 0));
        // 左侧：所有记录的累计分
        totalScoreLabel = new JLabel("所有记录累计加分: 0.0 分", SwingConstants.LEFT);
        totalScoreLabel.setFont(new Font("Arial", Font.BOLD, 14));
        // 右侧：当前查询人的总分（默认隐藏，查询后显示）
        personalTotalLabel = new JLabel("", SwingConstants.RIGHT);
        personalTotalLabel.setFont(new Font("Arial", Font.BOLD, 14));
        personalTotalLabel.setForeground(Color.RED);

        bottomPanel.add(totalScoreLabel, BorderLayout.WEST);
        bottomPanel.add(personalTotalLabel, BorderLayout.EAST);
        frame.add(bottomPanel, BorderLayout.SOUTH);

        frame.setVisible(true);
    }

    // 新增奖项并更新总表
    private void addAward() {
        // 输入校验
        String projectName = projectNameField.getText().trim();
        String studentName = addNameField.getText().trim();
        if (projectName.isEmpty() || studentName.isEmpty()) {
            JOptionPane.showMessageDialog(frame, "项目名称和学生姓名不能为空！", "输入错误", JOptionPane.ERROR_MESSAGE);
            return;
        }
        if (!aClassRadio.isSelected() && !bClassRadio.isSelected() && !cClassRadio.isSelected()) {
            JOptionPane.showMessageDialog(frame, "请选择奖项大类！", "输入错误", JOptionPane.ERROR_MESSAGE);
            return;
        }
        if (!nationalRadio.isSelected() && !provincialRadio.isSelected()) {
            JOptionPane.showMessageDialog(frame, "请选择奖项级别！", "输入错误", JOptionPane.ERROR_MESSAGE);
            return;
        }
        if (!firstPrizeRadio.isSelected() && !secondPrizeRadio.isSelected() && !thirdPrizeRadio.isSelected()) {
            JOptionPane.showMessageDialog(frame, "请选择奖项等次！", "输入错误", JOptionPane.ERROR_MESSAGE);
            return;
        }
        int personalRank = (Integer) personalRankCombo.getSelectedItem();
        int totalTeam = (Integer) totalTeamCombo.getSelectedItem();
        if (personalRank > totalTeam) {
            JOptionPane.showMessageDialog(frame, "个人排名不能大于合作总人数！", "输入错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        // 解析奖项信息
        String awardClass = aClassRadio.isSelected() ? "A类" : (bClassRadio.isSelected() ? "B类" : "C类");
        String awardLevel = nationalRadio.isSelected() ? "国家级" : "省部级";
        String awardPrize = firstPrizeRadio.isSelected() ? "一等奖" : (secondPrizeRadio.isSelected() ? "二等奖" : "三等奖");

        // 计算加分
        double baseScore = getBaseScore(awardClass, awardLevel, awardPrize);
        if (baseScore < 0) {
            JOptionPane.showMessageDialog(frame, "C类省部级三等奖不加分！", "提示", JOptionPane.INFORMATION_MESSAGE);
            return;
        }
        double contribution = getContribution(personalRank, totalTeam);
        double singleScore = Math.round(baseScore * contribution * 100.0) / 100.0;

        // 保存记录并更新总表
        Award award = new Award(projectName, awardClass, awardLevel, awardPrize, personalRank, totalTeam, singleScore, studentName);
        awardList.add(award);
        tableModel.addRow(new Object[]{
                projectName, awardClass, awardLevel, awardPrize, personalRank, totalTeam, singleScore
        });

        // 更新学生总分缓存
        studentTotalScores.put(studentName, studentTotalScores.getOrDefault(studentName, 0.0) + singleScore);
        // 更新底部总累计分
        updateTotalScore();

        // 清空新增奖项的输入框（不影响查询输入框）
        projectNameField.setText("");
        addNameField.setText("");
        clearRadioButtons();
    }

    // 查询个人总分并只显示该学生的记录
    private void queryPersonalScores() {
        String queryName = queryNameField.getText().trim();
        if (queryName.isEmpty()) {
            JOptionPane.showMessageDialog(frame, "请输入要查询的学生姓名！", "输入错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        // 筛选该学生的所有记录
        List<Award> personalAwards = awardList.stream()
                .filter(award -> award.getStudentName().equals(queryName))
                .collect(Collectors.toList());

        // 1. 更新表格：只显示该学生的记录
        queryTableModel.setRowCount(0);  // 清空查询表
        for (Award award : personalAwards) {
            queryTableModel.addRow(new Object[]{
                    award.getProjectName(), award.getAwardClass(), award.getAwardLevel(),
                    award.getAwardPrize(), award.getPersonalRank(), award.getTotalTeam(),
                    award.getSingleScore()
            });
        }
        awardTable.setModel(queryTableModel);  // 切换表格模型为个人查询表

        // 2. 计算并显示个人总分（含上限处理）
        double personalTotal = studentTotalScores.getOrDefault(queryName, 0.0);
        double effectiveTotal = Math.min(personalTotal, 2.5);  // 加分上限2.5分
        if (personalAwards.isEmpty()) {
            personalTotalLabel.setText(queryName + " 无奖项记录");
        } else {
            personalTotalLabel.setText(
                    String.format("%s 个人总加分: %.2f 分（有效分: %.2f 分）",
                            queryName, personalTotal, effectiveTotal)
            );
        }
    }

    // 更新所有记录的累计总分
    private void updateTotalScore() {
        double total = awardList.stream().mapToDouble(Award::getSingleScore).sum();
        total = Math.round(total * 100.0) / 100.0;
        totalScoreLabel.setText("所有记录累计加分: " + total + " 分");
    }

    // 基础分计算
    private double getBaseScore(String awardClass, String awardLevel, String awardPrize) {
        if (awardClass.equals("A类")) {
            if (awardLevel.equals("国家级")) {
                return awardPrize.equals("一等奖") ? 2.5 : (awardPrize.equals("二等奖") ? 2 : 1.5);
            } else {
                return awardPrize.equals("一等奖") ? 2 : (awardPrize.equals("二等奖") ? 1.5 : 1);
            }
        } else if (awardClass.equals("B类")) {
            if (awardLevel.equals("国家级")) {
                return awardPrize.equals("一等奖") ? 2 : (awardPrize.equals("二等奖") ? 1.5 : 1);
            } else {
                return awardPrize.equals("一等奖") ? 1.5 : (awardPrize.equals("二等奖") ? 1 : 0.5);
            }
        } else { // C类
            if (awardLevel.equals("国家级")) {
                return awardPrize.equals("一等奖") ? 1.5 : (awardPrize.equals("二等奖") ? 1 : 0.5);
            } else {
                return awardPrize.equals("三等奖") ? -1 : (awardPrize.equals("一等奖") ? 1 : 0.5);
            }
        }
    }

    // 贡献度计算
    private double getContribution(int personalRank, int totalTeam) {
        if (totalTeam < 1 || totalTeam > 11 || personalRank < 1 || personalRank > 11 || personalRank > totalTeam) {
            return 0.0;
        }
        return contributionTable[totalTeam - 1][personalRank - 1];
    }

    // 清空单选按钮
    private void clearRadioButtons() {
        aClassRadio.setSelected(false);
        bClassRadio.setSelected(false);
        cClassRadio.setSelected(false);
        nationalRadio.setSelected(false);
        provincialRadio.setSelected(false);
        firstPrizeRadio.setSelected(false);
        secondPrizeRadio.setSelected(false);
        thirdPrizeRadio.setSelected(false);
    }

    // 奖项实体类
    private class Award {
        private String projectName;
        private String awardClass;
        private String awardLevel;
        private String awardPrize;
        private int personalRank;
        private int totalTeam;
        private double singleScore;
        private String studentName;

        public Award(String projectName, String awardClass, String awardLevel, String awardPrize,
                     int personalRank, int totalTeam, double singleScore, String studentName) {
            this.projectName = projectName;
            this.awardClass = awardClass;
            this.awardLevel = awardLevel;
            this.awardPrize = awardPrize;
            this.personalRank = personalRank;
            this.totalTeam = totalTeam;
            this.singleScore = singleScore;
            this.studentName = studentName;
        }

        // Getter方法
        public String getProjectName() { return projectName; }
        public String getAwardClass() { return awardClass; }
        public String getAwardLevel() { return awardLevel; }
        public String getAwardPrize() { return awardPrize; }
        public int getPersonalRank() { return personalRank; }
        public int getTotalTeam() { return totalTeam; }
        public double getSingleScore() { return singleScore; }
        public String getStudentName() { return studentName; }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(CompetitionScoreCalculator::new);
    }
}